import { defineStore } from 'pinia'
import { computed, reactive } from 'vue'

interface ListItem {
  name: string
  path: string
  title: string
  keepAlive: boolean
}

const storeSetup = () => {
  const list = reactive<ListItem[]>([])
  const show = computed(() => list.length > 0)
  const nameList = computed(() => list.filter(item => item.keepAlive).map(item => item.name))

  const setPath = (name: string, path: string) => {
    list.filter(item => item.name === name).forEach(item => (item.path = path))
  }
  const delTabsItem = (index: number) => {
    list.splice(index, 1)
  }
  const setTabsItem = (data: ListItem) => {
    list.push(data)
  }
  const clearTabs = () => {
    list.splice(0, list.length)
  }
  const closeTabsOther = (data: ListItem[]) => {
    clearTabs()
    list.push(...data)
  }
  const closeCurrentTag = (data: {
    $route: { fullPath: string }
    $router: { push: (path: string) => void }
  }) => {
    for (let i = 0, len = list.length; i < len; i++) {
      const item = list[i]
      if (item.path === data.$route.fullPath) {
        if (i < len - 1) {
          data.$router.push(list[i + 1].path)
        } else if (i > 0) {
          data.$router.push(list[i - 1].path)
        } else {
          data.$router.push('/')
        }
        list.splice(i, 1)
        break
      }
    }
  }

  return {
    list,
    show,
    nameList,
    setPath,
    delTabsItem,
    setTabsItem,
    clearTabs,
    closeTabsOther,
    closeCurrentTag,
  }
}

export const useTabsStore = defineStore('tabs', storeSetup)
